package com.rockbb.common.utilities.internet;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;

import com.rockbb.common.utilities.text.StringUtils;

public class SmtpMailSender {

	private static final SmtpMailSender instance = new SmtpMailSender();

	private static Logger logger = Logger.getLogger(SmtpMailSender.class);
	private javax.mail.Session mailSession;

	private SmtpMailSender(){
		
	}

	public static SmtpMailSender getInstance() {
		return instance;
	}

	public void initMailSession(String host, String username, String password, boolean reset) {

		if (mailSession == null || reset) {
			logger.debug("Initializing or reseting");

			Properties props = java.lang.System.getProperties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");

			SmtpMailAuthBean myEmailAuther = 
				new SmtpMailAuthBean(username, password);

			mailSession = javax.mail.Session.getInstance(props, myEmailAuther);
			logger.debug("Initializing...[end]");
		} else {
			logger.debug("Initialized, skip.");
		}
	}

	public void sendmail(Email email)
			throws Exception {

		if (mailSession == null) {return;}

		Transport transport = mailSession.getTransport("smtp");
		MimeMessage mimeMsg = new MimeMessage(mailSession);
		
		if (email.getFromAddr() != null && email.getFromAddr().length() > 0) {
			InternetAddress sentFrom = new InternetAddress(email.getFromAddr());
			mimeMsg.setFrom(sentFrom);
		}
		mimeMsg.setSubject(email.getSubject(), email.getEncode());

		Multipart multipart = new MimeMultipart();// 附件传输格式

		List<String> attachmentList = email.getAttachmentList();
		if (attachmentList != null) {
			for (int i = 0; i < attachmentList.size(); i++) {
				MimeBodyPart messageBodyPart2 = new MimeBodyPart();
				// 选择出每一个附件名
				String attachment = attachmentList.get(i);
				String filename = attachment.split(",")[0];
				String displayname = attachment.split(",")[1];
				// 得到数据源
				FileDataSource fds = new FileDataSource(filename);
				// 得到附件本身并至入BodyPart
				messageBodyPart2.setDataHandler(new DataHandler(fds));
				// 得到文件名同样至入BodyPart
				messageBodyPart2.setFileName(MimeUtility.encodeText(displayname));
				multipart.addBodyPart(messageBodyPart2);
			}
		}

		MimeBodyPart messageBodyPart1 = new MimeBodyPart();
		messageBodyPart1.setContent(email.getBody(), "text/html;charset="+email.getEncode());

		multipart.addBodyPart(messageBodyPart1);
		mimeMsg.setContent(multipart);

		// 设定收件人，可多个
		String toAddrs = "";
		if (email.getToAddr() !=null && email.getToAddr().size() > 0) {
			toAddrs = StringUtils.implode(email.getToAddr(), ",");
			logger.debug("Recipients: " + toAddrs);
			mimeMsg.addRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, toAddrs);
		}

		// 设定抄送人，可多个
		String ccAddrs = "";
		if (email.getCcAddr() != null && email.getCcAddr().size() > 0) {
			ccAddrs = StringUtils.implode(email.getCcAddr(), ",");
			logger.debug("CC:" + ccAddrs);
			mimeMsg.addRecipients(javax.mail.internet.MimeMessage.RecipientType.CC, ccAddrs);			
		}

		String bccAddrs = "";
		if (email.getBccAddr() != null && email.getBccAddr().size() > 0) {
			ccAddrs = StringUtils.implode(email.getBccAddr(), ",");
			logger.debug("BCC:" + bccAddrs);
			mimeMsg.addRecipients(javax.mail.internet.MimeMessage.RecipientType.BCC, bccAddrs);			
		}

		// 设置信件头的发送日期
		mimeMsg.setSentDate(new Date());
		mimeMsg.saveChanges();

		Transport.send(mimeMsg);
		multipart.removeBodyPart(multipart.getCount()-1);
		transport.close();
	}
	
}

